import {devFirstShop, rootPath} from "../../../../shared/init"
import {DEV, env, HOST} from "../../../../shared/project-config"
import React from "react"
import {compose, withHandlers, withState, lifecycle} from "recompose"
import {postJSON, get, putJSON} from "../../../../shared/server"
import {message} from "antd"
import {read} from "zr-react-toolbox"
import {onComplete, createMap, map, mapData, locationAddress, addOneMarker} from "./map"

const getBase64 = (img, callback) => {
	const reader = new FileReader();
	reader.addEventListener('load', () => callback(reader.result));
	reader.readAsDataURL(img);
}


const firstShopCompose = compose(
	withState('_initData', '_setInitData', env === DEV ? devFirstShop : {}),
	withState('_submitting', '_setSubmitting', false),
	withState('_serverMessage', '_setServerMessage', null),
	withState('licenseServerFile', '$licenseServerFile', null),
	withState('idCardServerFile', '$idCardServerFile', null),
	withState('licensePicture', '$licensePicture', null),
	withState('idCardPicture', '$idCardPicture', null),
	withState('licensePictureUploading', '$licensePictureUploading', false),
	withState('idCardPictureUploading', '$idCardPictureUploading', false),
	withState('mapVisible', '$mapVisible', false),
	withState('addressSource', '$addressSource', []),
	withState('locationData', '$locationData', {}),
	withHandlers({
		onLocation: ({$locationData}) => {
			return ({lng, lat, address}) => {
				//拖动图标
				$locationData({lng, lat, address})
			}
		}
	}),
	withHandlers({
		showMap: ({$mapVisible, onLocation}) => {
			return () => {
				$mapVisible(true)
				if (!map) {
					setTimeout(() => {
						createMap({
							onComplete: onComplete({
								onLocation
							})
						})
					}, 500)
				}
			}
		},
		searchAddress: ({$addressSource}) => {
			return (value) => {
				$addressSource([])
				locationAddress(value, (result) => {
					$addressSource(result.poiList.pois || [])
				})
			}
		},
		selectAddress: ({addressSource, onLocation}) => {
			return (idx) => {
				const address = addressSource[idx]
				onLocation({...address.location, address: `${address.address}${address.name}`})
				addOneMarker({...address.location, onLocation})
			}
		},
		closeMap: ({$mapVisible, locationData, form}) => {
			return () => {
				$mapVisible(false)
				form.setFieldsValue({address: locationData.address})
			}
		},
		getShopData: ({_setInitData, $licensePicture, $idCardPicture}) => {
			return () => {
				get(`/myShop`)
					.then(data => {
						if (!data || data.length < 1) {
							return
						}
						const primaryData = Object.assign({}, data[0])
						primaryData.shopId = data.id
						delete primaryData['shopDetailList']
						const subShops = data[0]['shopDetailList']
						const subShop = subShops && subShops.length > 0 ? subShops[0] : {}
						subShop.primaryShopId = subShop.id
						const initData = {
							...primaryData,
							...subShop
						}
						initData.area = [subShop.province, subShop.city, subShop.county]
						$licensePicture(`${HOST}/file/image/${initData['licensePictureId']}`)
						$idCardPicture(`${HOST}/file/image/${initData['idCardPictureId']}`)
						_setInitData(initData)
					})
			}
		}
	}),
	withHandlers({
		submitForm: ({_setSubmitting, _setServerMessage, history}) => {
			return (formValue) => {
				postJSON('/myShop', formValue, true).then(data => {
					history.push(`/${rootPath}/my-shop`)
				}).catch(error => {
					_setServerMessage(error.message)
					message.error(`提交失败,原因:${error.message}`)
				}).finally(() => {
					_setSubmitting(false)
				})
			}
		},
		updateForm: ({_setSubmitting, _setServerMessage, history, _initData}) => {
			return (formValue) => {
				formValue.shopId = _initData.shopId
				formValue.primaryShopId = _initData.primaryShopId
				putJSON('/myShop', formValue, true).then(data => {
					history.push(`/${rootPath}/my-shop`)
				}).catch(error => {
					_setServerMessage(error.message)
					message.error(`提交失败,原因:${error.message}`)
				}).finally(() => {
					_setSubmitting(false)
				})
			}
		},
	}),
	withHandlers({
		onFileUploadChange: () => {
			return (setLoading, setFile, setServerFile) => (info) => {
				setLoading(info.file.status === 'uploading')
				if (info.file.status === 'done') {
					setServerFile(read(info, 'file.response.data'))
					getBase64(info.file.originFileObj, (url) => {
						setFile(url)
						setLoading(false)
					})
				}
			}
		}
	}),
	withHandlers({
		onLicenseChange: ({onFileUploadChange, $licensePicture, $licensePictureUploading, $licenseServerFile}) => {
			return onFileUploadChange($licensePictureUploading, $licensePicture, $licenseServerFile)
		},
		onIdCardChange: ({onFileUploadChange, $idCardPicture, $idCardPictureUploading, $idCardServerFile}) => {
			return onFileUploadChange($idCardPictureUploading, $idCardPicture, $idCardServerFile)
		}
	}),
	withHandlers({
		onSubmit: ({_setSubmitting, form, submitForm, updateForm, idCardServerFile, licenseServerFile, mode}) => {
			return () => {
				_setSubmitting(true)
				form.validateFieldsAndScroll(null, {scroll: {offsetTop: 15}}, (err, values) => {
					if (err) {
						_setSubmitting(false)
						return
					}
					values.idCardPictureId = read(idCardServerFile, "id")
					values.licensePictureId = read(licenseServerFile, "id")
					if (mode === 'edit') {
						updateForm(values)
					} else {
						submitForm(values)
					}

				})
			}
		}
	}),
	lifecycle({
		componentDidMount() {
			const {mode, getShopData} = this.props
			if (mode === 'edit') {
				getShopData()
			}
		}
	})
)

export default firstShopCompose
